/* global chrome */
'use strict'
import EventEmitter from './EventEmitter'
export default class Client extends EventEmitter {
  constructor (host, port) {
    super()
    this.host = host
    this.port = port
    this.init()
  }
  init () {
    let self = this
    chrome.sockets.tcp.create((info) => {
      if (info.socketId) {
        chrome.sockets.tcp.getInfo(info.socketId, (socketInfo) => {
          self.info = socketInfo
        })
        chrome.sockets.tcp.connect(info.socketId, self.host, self.port, (result) => {
          if (result === 0) {
            chrome.sockets.tcp.onReceive.addListener(self.onReceive.bind(this))
            chrome.sockets.tcp.onReceiveError.addListener(self.onReceiveError.bind(this))
            this.emit('connect')
          } else {
            this.emit('error')
          }
        })
      }
    })
  }
  onReceive (info) {
    if (info.socketId === this.info.socketId) {
      this.emit('data', info)
    }
  }
  onReceiveError (info) {
    if (info.socketId === this.info.socketId) {
      this.emit('receiveError')
    }
  }
  send (data) {
    if (!this.info.connected) {
      this._send(data)
    } else {
      let self = this
      chrome.sockets.tcp.connect(this.info.socketId, this.host, this.port, function (result) {
        if (result === 0) {
          self._send(data)
        }
      })
    }
  }
  _send (data) {
    chrome.sockets.tcp.send(this.info.socketId, data, (info) => {
      if (info.resultCode === 0) {
        this.emit('send')
      } else {
        this.emit('sendError')
      }
    })
  }
  close () {
    chrome.sockets.tcp.close(this.info.socketId, () => {
      this.emit('close')
    })
  }

}
